<template>
  <div class="menu section-container">
    <div class="section-title">菜单管理</div>
    <div class="setting-actions">
      <div class="actions-left">
        <el-button v-permission="['setting:menu:menu:add']" type="primary" @click="handleAddMenu()">添加菜单</el-button>
        <el-button v-permission="['setting:menu:menu:delete']" @click="handleDeleteMenu()" :disabled="deleteMenuList.length === 0">删除</el-button>
      </div>
    </div>
    <el-tabs v-model="activeModule" @tab-change="handleChangeModule">
      <el-tab-pane v-for="(item, index) in moduleList" :key="index" :label="item.name" :name="item.id"></el-tab-pane>
    </el-tabs>
    <div class="menu-tree-box">
      <div class="tree-header">
        <span class="tree-header-title">菜单名称</span>
        <span class="tree-header-icon">图标</span>
        <span class="tree-header-url">路由url</span>
        <span class="tree-header-type">菜单类型</span>
        <span>是否启用</span>
        <span class="tree-header-option">操作</span>
      </div>
      <el-tree
        v-loading="treeLoading"
        ref="menuTreeRef"
        :data="moduleMenu"
        :props="menuTreeProps"
        node-key="id"
        show-checkbox
        :expand-on-click-node="true"
        :indent="0"
        class="tree-content"
        @check="handleCheckMenu"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <div class="tree-node-label" :style="{ paddingLeft: (node.level - 1) * 10 + 'px' }">{{ node.label }}</div>
            <div class="tree-node-icon"><Icon :name="data.icon" /></div>
            <div class="tree-node-path">{{ data.path }}</div>
            <div class="tree-node-type">
              {{ data.type === 1 ? '菜单分类' : '菜单页面' }}
            </div>
            <div class="tree-node-use" @click.stop>
              <el-switch v-permission="['setting:menu:menu:edit']" v-model="data.isuse" :before-change="changeIsUse.bind(this, data)" :loading="optionLoading && menuForm.id === data.id" />
            </div>
            <div class="tree-options">
              <div class="button-box">
                <el-button v-permission="['setting:menu:menu:edit']" type="primary" text @click.stop="handleEditMenu(data)" style="margin-right: 10px">编辑</el-button>
                <el-dropdown>
                  <i class="iconfont">&#xe771;</i>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-if="data.type === 1"><span v-permission="['setting:menu:menu:add']" @click.stop="handleAddMenu(data)">添加菜单</span></el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <el-button type="primary" text v-if="data.type === 2" @click.stop="handleFuncSetting(data)">功能配置</el-button>
            </div>
          </div>
        </template>
      </el-tree>
    </div>
    <el-dialog v-model="menuDialog" :title="menuForm.id ? '修改菜单' : '添加菜单'" width="680px" :draggable="true" @close="resetMenuForm">
      <el-form :model="menuForm" label-width="100px" label-position="left" ref="menuFormRef" :rules="menuFormRules" :inline-message="true">
        <el-form-item label="上级菜单:" prop="pid">
          <el-tree-select
            v-model="menuForm.pid"
            placeholder="选择所属上级菜单"
            :data="pageParMenuOpt"
            default-expand-all
            :check-strictly="true"
            :props="menuTreeProps"
          ></el-tree-select>
        </el-form-item>
        <el-form-item label="菜单类型:" prop="type">
          <el-radio-group v-model="menuForm.type" @change="changeMenuType">
            <el-radio :label="1" border>分类</el-radio>
            <el-radio :label="2" border style="margin-left: 10px">页面</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属模块:" :prop="menuForm.type === 1 ? 'moduleId' : ''">
          <el-select v-model="menuForm.moduleId" placeholder="请选择所属模块">
            <el-option v-for="item in moduleList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单域名:" prop="host">
          <el-input v-model="menuForm.host" placeholder="请输入域名" />
        </el-form-item>
        <el-form-item label="菜单名称:" prop="title">
          <el-input v-model="menuForm.title" />
        </el-form-item>
        <el-form-item label="路由url:" prop="path">
          <el-input v-model="menuForm.path" @change="generateNameComponent" />
        </el-form-item>
        <el-form-item label="菜单英文名:" prop="name">
          <el-input :disabled="!menuForm.path" v-model="menuForm.name" />
        </el-form-item>
        <el-form-item label="文件目录:" :prop="menuForm.type === 2 ? 'component' : ''">
          <el-input :disabled="!menuForm.path" v-model="menuForm.component" />
        </el-form-item>
        <el-form-item label="拓展设置:">
          <div class="expand-list">
            <div class="expand-item">
              <span>是否启用：</span>
              <el-switch v-model="menuForm.isuse"></el-switch>
            </div>
            <div class="expand-item">
              <span>是否公共：</span>
              <el-switch v-model="menuForm.isOpen"></el-switch>
            </div>
            <div class="expand-item">
              <span>是否频道：</span>
              <el-switch v-model="menuForm.isChannel" />
            </div>
            <div class="expand-item">
              <span>显示头部：</span>
              <el-switch v-model="menuForm.isShowHeader"></el-switch>
            </div>
            <div class="expand-item">
              <span>显示侧边栏：</span>
              <el-switch v-model="menuForm.isShowSidebar"></el-switch>
            </div>
            <div class="expand-item">
              <span>显示面包屑：</span>
              <el-switch v-model="menuForm.isShowCrumb"></el-switch>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="显示排序:" prop="level">
          <el-input-number v-model="menuForm.level" :min="1" :max="9999" :precision="0"  />
        </el-form-item>
        <el-form-item label="图标:" prop="icon">
          <IconSelect v-model:currentIcon="menuForm.icon" />
        </el-form-item>
        <el-form-item label="菜单描述:" prop="description">
          <el-input v-model="menuForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" :loading="optionLoading" @click="handleSubmitMenu">确认</el-button>
          <el-button @click="menuDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <el-drawer v-model="funcDrawer" direction="rtl" size="55%" :title="currentMenu?.title">
      <div class="func-setting-title">
        <div class="left">
          <el-button v-permission="['setting:menu:menu:add']" type="primary" @click="handleAddFunc(1)">添加功能</el-button>
          <el-button v-permission="['setting:menu:menu:delete']" @click="handleDeleteFunc" style="margin-left: 10px" :disabled="deleteFuncList.length === 0">删除</el-button>
        </div>
        <div class="slot-label">
          <el-button>
            显示所有
            <PopoverTip :content="'用于显示/隐藏功能页面，开启后显示所有菜单'" />
            <el-switch v-model="showPermission" @change="handleChangePermissionShow" :active-value="1" :inactive-value="0" />
          </el-button>
        </div>
      </div>
      <div class="func-setting">
        <el-table
          :data="funcTableData"
          style="width: 100%"
          v-loading="tableLoading"
          @selection-change="handleCheckFunc"
          ref="funcTableRef"
          row-key="id"
          lazy
          :load="loadFunc"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="名称" prop="title" width="200" />
          <el-table-column label="路由" prop="path" />
          <el-table-column label="权限标识" prop="permission" />
          <el-table-column label="类型" width="130">
            <template #default="scope">
              <span>
                {{ scope.row.type === 3 ? '功能页面' : '功能按钮' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="150">
            <template #default="scope">
              <el-button v-permission="['setting:menu:menu:edit']" size="small" @click="handleEditFunc(scope.row)" style="margin-right: 8px">编辑</el-button>
              <el-dropdown class="el-dropdown-box">
                <el-button size="small" class="more-dropdown-btn"><i class="iconfont more">&#xe6dc;</i></el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-if="scope.row.type === 3">
                      <span v-permission="['setting:menu:menu:add']" @click="handleAddFunc(2, scope.row)">添加功能</span>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <span v-permission="['setting:menu:menu:delete']" @click="handleDeleteFunc(scope.row)">删除</span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog v-model="funcDialog" :title="funcForm.id ? '修改功能' : '添加功能'" width="680px" :draggable="true" @close="resetFuncForm">
          <!-- 功能按钮与功能页面的差别除了表单项，还有上级菜单选项 -->
          <el-form :model="funcForm" label-width="120px" label-position="left" ref="funcFormRef" :rules="funcFormRules" :inline-message="true">
            <el-form-item label="上级菜单:" prop="pid">
              <el-tree-select
                v-model="funcForm.pid"
                placeholder="选择所属上级菜单"
                :data="funcParMenuOpt"
                default-expand-all
                :props="menuTreeProps"
                :check-strictly="true"
                disabled
              ></el-tree-select>
            </el-form-item>
            <el-form-item label="功能类型:" prop="type">
              <el-radio-group v-model="funcForm.type" @change="handleChangeFuncType">
                <el-radio :label="3" border style="margin-right: 10px">页面</el-radio>
                <el-radio :label="4" border>按钮</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="功能名称:" prop="title">
              <el-input v-model="funcForm.title" placeholder="请输入功能名称" />
            </el-form-item>
            <!-- 页面 -->
            <div v-if="funcForm.type === 3">
              <el-form-item label="路由url:" prop="path">
                <el-input v-model="funcForm.path" placeholder="请输入路由url" @change="generateNameComponent" />
              </el-form-item>
              <el-form-item label="功能英文名:" prop="name">
                <el-input v-model="funcForm.name" placeholder="请输入功能英文名" />
              </el-form-item>
              <el-form-item label="文件目录:" v-if="funcForm.type === 3" prop="component">
                <el-input v-model="funcForm.component" placeholder="请输入文件目录" />
              </el-form-item>
              <el-form-item label="权限标识:" prop="permission">
                <el-input v-model="funcForm.permission" placeholder="请输入权限标识，格式为xx:xx:xx" />
              </el-form-item>
              <el-form-item label="" prop="authorityIds">
                <template #label>
                  <div class="slot-label">
                    关联接口
                    <PopoverTip :content="'选择接口权限关联当前按钮'" />
                    :
                  </div>
                </template>
                <el-tree-select
                  v-model="funcForm.authorityIds"
                  :data="interfaceTreeData"
                  :props="interfaceTreeProps"
                  :filter-node-method="filterInterface"
                  node-key="id"
                  filterable
                  multiple
                  placeholder="请选择接口权限进行关联"
                  style="width: 100%;"
                />
              </el-form-item>
            </div>
            <!-- 按钮 -->
            <div v-if="funcForm.type === 4">
              <el-form-item label="权限标识:" prop="permission">
                <el-input v-model="funcForm.permission" placeholder="请输入权限标识，格式为xx:xx:xx" />
              </el-form-item>
              <el-form-item label="" v-if="funcForm.type === 4" prop="funMenuIds">
                <template #label>
                  <div class="slot-label">
                    关联页面
                    <PopoverTip :content="'选择页面关联当前按钮'" />
                    :
                  </div>
                </template>
                <el-tree-select
                  v-model="funcForm.funMenuIds"
                  placeholder="请选择功能页面进行关联"
                  collapse-tags-tooltip
                  multiple
                  :data="funcTreeData"
                  :props="menuTreeProps"
                  style="width: 100%;"
                ></el-tree-select>
              </el-form-item>
              <el-form-item label="" v-if="funcForm.type === 4" prop="authorityIds">
                <template #label>
                  <div class="slot-label">
                    关联接口
                    <PopoverTip :content="'选择接口权限关联当前按钮'" />
                    :
                  </div>
                </template>
                <el-tree-select
                  v-model="funcForm.authorityIds"
                  :data="interfaceTreeData"
                  :props="interfaceTreeProps"
                  :filter-node-method="filterInterface"
                  node-key="id"
                  filterable
                  multiple
                  placeholder="请选择接口权限进行关联"
                  style="width: 100%;"
                />
              </el-form-item>
            </div>
            <el-form-item label="拓展设置:">
              <div class="expand-list">
                <div class="expand-item">
                  <span>是否启用：</span>
                  <el-switch v-model="funcForm.isuse"></el-switch>
                </div>
                <div class="expand-item">
                  <span>是否公共：</span>
                  <el-switch v-model="menuForm.isOpen"></el-switch>
                </div>
                <div class="expand-item" v-if="funcForm.type === 3">
                  <span>是否显示：</span>
                  <el-switch v-model="funcForm.isPermissionShow" :active-value="1" :inactive-value="0" />
                </div>
                <div class="expand-item" v-if="funcForm.type === 3">
                  <span>是否频道：</span>
                  <el-switch v-model="funcForm.isChannel" />
                </div>
                <div class="expand-item" v-if="funcForm.type === 3">
                  <span>显示头部：</span>
                  <el-switch v-model="funcForm.isShowHeader"></el-switch>
                </div>
                <div class="expand-item" v-if="funcForm.type === 3">
                  <span>显示侧边栏：</span>
                  <el-switch v-model="funcForm.isShowSidebar"></el-switch>
                </div>
                <div class="expand-item" v-if="funcForm.type === 3">
                  <span>显示面包屑：</span>
                  <el-switch v-model="funcForm.isShowCrumb"></el-switch>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="功能描述:">
              <el-input v-model="funcForm.description" type="textarea" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button type="primary" @click="handleSubmitFunc()">确认</el-button>
              <el-button @click="funcDialog = false">取消</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
// 获取整个菜单列表
/*
 * 1：菜单分类
 * 2：菜单页面
 * 3：功能页面
 * 4：功能按钮
 * */
import { addMenuFunc, editMenuFunc, deleteMenuFunc, getMenuList } from '@/api/role'
import { getModuleList } from '@/api/setting'
import { getAuthorityTree } from '@/api/auth'
import { ref, reactive, computed, onMounted } from 'vue'
import { createTreeData } from '@/utils/setting'
import { ElMessage, ElMessageBox } from 'element-plus'
import { IconSelect, Icon } from '@ruifox-cms/components'

const optionLoading = ref(false)

// 接口列表获取
const interfaceTreeProps = {
  value: 'id',
  label: 'name',
  children: 'authorityList'
}
const interfaceTreeData = ref([])
const _getAuthorityTree = async () => {
  const res = await getAuthorityTree()
  if (res.code === 20000) {
    interfaceTreeData.value = res.data
  }
}
_getAuthorityTree()

// 接口筛选
const filterInterface = (value, data) => {
  return data.title.includes(value)
}

// 模块获取
const activeModule = ref('')
const moduleList = ref([])
const _getModuleList = async () => {
  const res = await getModuleList()
  if (res.code === 20000) {
    moduleList.value = res.data
    activeModule.value = res.data[0].id
  }
}

const handleChangeModule = () => {
  deleteMenuList.value = []
}

// 当前模块菜单列表
const moduleMenu = computed(() => {
  console.log(allModuleMenu.value.filter(item => item.moduleId === activeModule.value), 89898999)
  return allModuleMenu.value.filter(item => item.moduleId === activeModule.value)
})
const menuTreeProps = {
  value: 'id',
  children: 'children',
  label: function (data){
    return data.title
  }
}
// 菜单分类与菜单页面功能页面的上级菜单选项
const pageParMenuOpt = ref([
  //根目录
  {
    id: 0,
    type: 1,
    title: '系统',
    children: []
  }
])
// 获取所有菜单，做分类处理
const treeLoading = ref(false)
const allModuleMenu = ref([])
const handleGetAllMenu = async () => {
  treeLoading.value = true
  const res = await getMenuList({ types: '1,2' })
  if(res.code === 20000){
    const treeData = createTreeData(res.data)
    pageParMenuOpt.value[0].children = treeData
    allModuleMenu.value = treeData
  }
  treeLoading.value = false
}
// 公共表单校验方法
const validatorComponent = (rule, value, callback) => {
  if (!value && (menuForm.type === 2 || menuForm.type === 3)) {
    callback(new Error('请输入前端文件目录'))
  } else {
    callback()
  }
}
const validatorPath = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入路由url'))
  } else {
    if (!value.startsWith('/')) {
      callback(new Error('请以/开头'))
    } else {
      callback()
    }
  }
}

// 生成name和component
const generateNameComponent = (url) => {
  if (!url.startsWith('/') || ![1,2,3].includes(menuForm.type)) return
  const cleanUrl = url.startsWith('/') ? url.slice(1) : url
  const words = cleanUrl.split('/')
  menuForm.name = words.map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('')

  if (menuForm.type == 2 || menuForm.type == 3) {
    menuForm.component = `/${words.map((word, index) => 
      index === words.length - 1 ? word.charAt(0).toUpperCase() + word.slice(1) : word).join('/')}`
  }
}
/*****************************************************菜单分类与页面添加/编辑**********************************************/
const menuDialog = ref(false)
const menuFormRef = ref(null)
const menuFormRules = reactive({
  pid: [{ required: true, trigger: 'blur' }],
  title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  name: [{ required: true, message: '请输入菜单英文名', trigger: 'change' }],
  path: [{ required: true, validator: validatorPath, trigger: 'blur' }],
  component: [{ validator: validatorComponent, trigger: 'change' }],
  type: [{ required: true, trigger: 'blur' }],
  isuse: [{ required: true, trigger: 'blur' }],
  moduleId: [{ required: true, message: '所属模块不能为空', trigger: 'blur' }]
})
const defaultMenuForm = {
  id: null,
  title: '', //菜单名称
  name: '', //英文名
  path: '', //路径
  component: '', //前端文件地址
  pid: 0, //父级菜单id
  isuse: true, //是否启用
  isshow: true, //是否显示（表单不做填写）
  icon: '', //图标
  type: 2, //类型
  description: '', //描述
  isShowHeader: true, //是否显示头部
  isShowSidebar: true, //是否显示侧边栏
  isShowCrumb: true, //是否显示面包屑
  isChannel: false, //是否频道页
  authorityIds: [], //接口权限关联
  funMenuIds: [], //功能页面关联
  isPermissionShow: 1, //是否显示
  level: 1 //层级
}
const menuForm = reactive(Object.assign({}, defaultMenuForm))

// 添加菜单
const handleAddMenu = (data) => {
  Object.assign(menuForm, defaultMenuForm)
  if(data) {
    menuForm.pid = data.id
  } else {
    menuForm.pid = 0
  }
  menuDialog.value = true
}

// 编辑菜单
const handleEditMenu = (data) => {
  Object.assign(menuForm, data)
  menuDialog.value = true
}

// 菜单表单项切换类型
const changeMenuType = (val) => {
  if(val === 1) {
    menuForm.component = ''
  }
}

// 切换菜单启用状态
const changeIsUse = (data) => {
  Object.assign(menuForm, data)
  menuForm.isuse = !menuForm.isuse
  optionLoading.value = true
  return new Promise((resolve,reject) => {
    editMenuFunc(menuForm).then((res) => {
      if (res.code === 20000) {
        optionLoading.value = false
        ElMessage({
          showClose: true,
          message: '修改成功',
          type: 'success',
        })
        handleGetAllMenu()
        return resolve(true)
      }else{
        return reject(new Error('Error'))
      }
    })
  })
}

// 提交菜单
const handleSubmitMenu = async () => {
  menuFormRef.value.validate(async valid => {
    if (valid) {
      optionLoading.value = true
      let res
      if(menuForm.id) {
        res = await editMenuFunc(menuForm)
      }else{
        res = await addMenuFunc(menuForm)
      }
      if(res.code === 20000) {
        const msg = menuForm.id? '修改成功' : '添加成功'
        ElMessage.success(msg)
        optionLoading.value = false
        menuDialog.value = false
        handleGetAllMenu()
      }
    }
  })
}

// 删除菜单
const menuTreeRef = ref(null)
const handleDeleteMenu = async (data) => {
  let _deleteList
  if(data){
    _deleteList = [data.id]
  }else{
    _deleteList = menuTreeRef.value.getCheckedKeys()
  }
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除所选菜单？</p><span style="font-size: 14px;color: #FF5240;">删除后菜单将被移除</span></div>', '删除确认', {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    }).then(() => {
      deleteMenuFunc({ menuList: _deleteList }).then(() => {
        deleteMenuList.value = []
        handleGetAllMenu()
        ElMessage.success('删除成功')
      })
    })
}

// 选中菜单
const deleteMenuList = ref([])
const handleCheckMenu = () => {
  deleteMenuList.value = menuTreeRef.value.getCheckedKeys()
}


// 关闭弹窗重置表单
const resetMenuForm = () => {
  menuFormRef.value.resetFields()
  Object.assign(menuForm, defaultMenuForm)
}
/*************************************************功能页面与按钮添加/编辑**********************************/
const funcDrawer = ref(false)
const currentMenu = ref(null)
const handleFuncSetting = (data) => {
  currentMenu.value = data
  handleGetMenuFunc()
  deleteFuncList.value = []
  funcDrawer.value = true
}

// 获取当前菜单页面下的功能页面与按钮
const tableLoading = ref(false)
const funcTableData = ref([])
const funcTableRef = ref(null)
const funcTreeData = computed(() => {
  const curMenuFuncPage = funcTableData.value.filter(item => item.type === 3)
  return [
    {
      id: 0,
      title: '当前菜单',
      children: curMenuFuncPage
    },
    {
      id: 1,
      title: '全部菜单',
      children: pageParMenuOpt.value
    }
  ]
})
const handleGetMenuFunc = async () => {
  tableLoading.value = true
  const res = await getMenuList({ pid: currentMenu.value.id, isPermissionShow: showPermission.value ? null : 1, types: '3,4' })
  if(res.code === 20000){
    funcTableData.value = res.data
  }
  tableLoading.value = false
}

// 切换显示权限功能
const showPermission = ref(1)
const handleChangePermissionShow = () => {
  handleGetMenuFunc()
}

// 加载功能
const loadFunc = async (row, treeNode, resolve) => {
  let res = await getMenuList({ pid: row.id, isPermissionShow: showPermission.value ? null : 1, types: '3,4' })
  resolve(res.data)
}

// 添加功能页面或按钮
const funcDialog = ref(false)
const funcFormRef = ref(null)
const funcFormRules = reactive({
  pid: [{ required: true, trigger: 'blur' }],
  title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  name: [{ required: true, message: '请输入菜单英文名', trigger: 'change' }],
  path: [{ required: true, validator: validatorPath, trigger: 'blur' }],
  component: [{ required: true, validator: validatorComponent, trigger: 'change' }],
  type: [{ required: true, trigger: 'blur' }],
  isuse: [{ required: true, trigger: 'blur' }]
})
const defaultFuncForm = reactive({
  id: null,
  title: '', //菜单名称
  name: '', //英文名
  path: '', //路径
  component: '', //前端文件地址
  pid: 0, //父级菜单id
  isuse: true, //是否启用
  isshow: true, //是否显示（表单不做填写）
  icon: '', //图标
  type: 4, //类型
  description: '', //描述
  isShowHeader: true, //是否显示头部
  isShowSidebar: true, //是否显示侧边栏
  isShowCrumb: true, //是否显示面包屑
  isChannel: false, //是否频道页
  authorityIds: [], //接口权限关联
  funMenuIds: [], //功能页面关联
  isPermissionShow: 1, //是否显示
  permission: "",
  host: ''
})
const funcForm = reactive(Object.assign({}, defaultFuncForm))

// 添加功能
const funcWay = ref(1) // 添加对象，1：菜单页面下添加，2：功能页面下添加（二者的上级菜单候选项不同）
const funcParMenuOpt = ref([])
const handleAddFunc = (type, data) => {
  Object.assign(funcForm, defaultFuncForm)
  funcWay.value = type
  if(type === 1) {
    funcForm.pid = currentMenu.value.id
    funcParMenuOpt.value = pageParMenuOpt.value
  }else{
    funcForm.pid = data.id
    funcForm.type = 4
    funcParMenuOpt.value = funcTableData.value.filter(item => item.type === 3)
  }
  funcDialog.value = true
}

// 切换功能类型
const handleChangeFuncType = (type) => {
  if(type === 3) {
    funcForm.isShowHeader = true
    funcForm.isShowSidebar = true
    funcForm.isShowCrumb = true
    funcForm.isChannel = false
    funcForm.host = currentMenu.value.host
  }
}

// 编辑功能
const handleEditFunc = (data) => {
  Object.assign(funcForm, data)
  const type = data.pid === currentMenu.value.id ? 1 : 2
  funcWay.value = type
  if(type === 1) {
    funcParMenuOpt.value = pageParMenuOpt.value
  }else{
    funcParMenuOpt.value = funcTableData.value.filter(item => item.type === 3)
  }
  funcDialog.value = true
}

// 提交功能
const handleSubmitFunc = async () => {
  funcFormRef.value.validate(async valid => {
    if (valid) {
      optionLoading.value = true
      let res
      if(funcForm.id) {
        res = await editMenuFunc(funcForm)
      }else{
        res = await addMenuFunc(funcForm)
      }
      if(res.code === 20000) {
        const msg = funcForm.id? '修改成功' : '添加成功'
        ElMessage.success(msg)
        optionLoading.value = false
        funcDialog.value = false
        handleGetMenuFunc()
      }
    }
  })
}

// 删除功能
const handleDeleteFunc = async (data) => {
  let _deleteList
  if(data){
    _deleteList = [data.id]
  }else{
    _deleteList = deleteFuncList.value
  }
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除所选功能？</p><span style="font-size: 14px;color: #FF5240;">删除后功能将被移除</span></div>', '删除确认', {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    }).then(() => {
      deleteMenuFunc({ menuList: _deleteList }).then(() => {
        deleteFuncList.value = []
        handleGetMenuFunc()
        ElMessage.success('删除成功')
      })
    })
}

// 选中功能
const deleteFuncList = ref([])
const handleCheckFunc = () => {
  deleteFuncList.value = funcTableRef.value.getCheckedKeys()
}

// 关闭弹窗重置表单
const resetFuncForm = () => {
  funcFormRef.value.resetFields()
  Object.assign(funcForm, defaultFuncForm)
}

onMounted(async () => {
  await _getModuleList()
  await handleGetAllMenu()
})
</script>

<style scoped lang="scss">
.setting-content {
  .menu-search-wrap {
    margin-top: 20px;
    display: flex;
    ::v-deep .el-form-item {
      margin-right: 36px;
      margin-bottom: 0;
    }
  }
  .header-option {
    display: flex;
    justify-content: space-between;
    .menu-search-btn {
      i {
        color: $mainColor;
      }
    }
    .menu-search-btn.show-search-wrap {
      border-color: $mainColor;
      color: $mainColor;
    }
  }
}
.menu-tree-box {
  .custom-tree-node {
    display: flex;
  }
  .tree-header {
    height: 40px;
    background-color: #f8f8f8;
    box-sizing: border-box;
    border-bottom: 1px solid #e4e4e4;
    padding-left: 46px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    span {
      flex-grow: 1;
      font-size: 14px;
    }
    span.tree-header-title,
    span.tree-header-icon {
      width: 140px;
      flex-grow: 0;
    }
    span.tree-header-url {
      width: 350px;
      flex-grow: 0;
    }
    span.tree-header-type {
      width: 280px;
      flex-grow: 0;
    }
    span.tree-header-option {
      width: 80px;
      flex-grow: 0;
    }
  }
  .tree-content {
    ::v-deep .el-tree-node .el-tree-node__content {
      border-bottom: 1px solid $borderColor;
      height: 48px;
    }
    ::v-deep .el-tree-node__label {
      width: 100%;
      .custom-tree-node {
        display: flex;
        justify-content: space-between;
        align-items: center;
        div {
          flex-grow: 1;
          box-sizing: border-box;
        }
        .tree-node-label,
        .tree-node-icon {
          width: 140px;
          flex-grow: 0;
        }
        .tree-node-path {
          width: 350px;
          flex-grow: 0;
        }
        .tree-node-type {
          width: 280px;
          flex-grow: 0;
        }
        .tree-options {
          display: flex;
          flex-direction: row-reverse;
          padding-right: 40px;
          div.button-box {
            flex-grow: 0;
            position: relative;
            i {
              position: absolute;
              right: 0;
              top: 8px;
              color: $mainColor;
            }
          }
        }
      }
    }
  }
}
.func-setting-title {
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  .fun-search-btn {
    i {
      color: $mainColor;
    }
  }
  .fun-search-btn.show-search-wrap {
    border-color: $mainColor;
    color: $mainColor;
  }
}
.func-setting {
  background-color: $white;
  border: 1px solid $borderColor;
  border-bottom: 0;
  ::v-deep .el-table th {
    background-color: $backBase;
  }
}
.el-form-item {
  margin-bottom: 10px;
}
.func-search-wrap {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  ::v-deep .el-form-item {
    margin-right: 36px;
    margin-bottom: 0;
  }
  .left,
  .right {
    display: flex;
  }
}
.slot-label {
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-dropdown-box {
  cursor: pointer;
  .more-dropdown-btn {
    padding-left: 0;
    padding-right: 0;
  }
  i {
    color: $mainColor;
    font-size: 20px;
  }
}

.expand-list {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  .expand-item {
    display: flex;
    align-items: center;
    margin-right: 20px;
    width: calc((100% - 60px) / 3);
    font-size: 12px;
    color: #606266;
  }
}
</style>
